﻿using ALRiskCloud;
using Aliyun.Acs.Jaq.Model.V20161123;
using DTCash.Logger;
using DTCash.Logger.DTO;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using DTCash.Logger.NodeLog;
using DTCash.Logger.NodeLog.Model;
using Uranus.Common;
using Uranus.WeiStationAPI.Models;

namespace Uranus.WeiStationAPI.Common
{
    public class CommonModel
    {

        /// <summary>
        /// 是否开发环境
        /// </summary>
        public static bool EnDebug
        {
            get
            {
                string version = ConfigurationManager.AppSettings["EnDebug"] ?? "false";
                return Convert.ToBoolean(version);
            }
        }

        /// <summary>
        /// 把金额转换成万元
        /// </summary>
        /// <param name="price"></param>
        /// <returns></returns>
        public static string PriceCalc(decimal price)
        {
            return
            price % 10000 == 0
                ? (price / 10000).ToString("f0")
                : price % 1000 == 0
                    ? (price / 10000).ToString("f1")
                    : price % 100 == 0
                        ? (price / 10000).ToString("f2")
                        : price % 10 == 0 ? (price / 10000).ToString("f3") : (price / 10000).ToString();
        }

        #region 发送短信
        public static bool SendSmms(string chanel, string mobile, string content)
        {
            if (string.IsNullOrEmpty(chanel))
            {
                chanel = ConfigurationManager.AppSettings["chanle"];
            }
            string result = RequestCommon.SimulationHttp(ConfigCenterWork.GetConfigValueByOperationType(3).ToString(),
               string.Format("chanle={0}&mobile={1}&content={2}", chanel, mobile, content),
               "post");

            return result.Contains("success");
        }
        #endregion
        internal static Regex PassWordRegex = new Regex("password=.*?&", RegexOptions.IgnoreCase);


        /// <summary>
        /// 验证版本
        /// </summary>
        /// <returns></returns>
        public static bool VerificationVersion()
        {
            try
            {
                string result = Uranus.Common.RequestCommon.SimulationHttp(ChinapnrAPI.ChinapnrCommon.ChinaReceiveUrl, "", "get");
                string version = ConfigurationManager.AppSettings["ChinaVersion"];
                if (string.Equals(result, version))
                    return true;
                else
                {
                    LogHelper.WriteLog(LogEnum.Info, "web网站与后台对比版本失败",
                                       string.Format("[时间]:{0} \r\n[当前版本号]:{1}\r\n[汇付接收后台版本号]:{2}",
                                                     DateTime.Now.ToLocalTime(), version, result), true);
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogEnum.Error, "验证版本", ex.ToString());
                return false;
            }
        }

        public static readonly string RequestDecryptKey = ConfigurationManager.AppSettings["RequestDecryptKey"];

        /// <summary>
        /// 获取提现手续费
        /// </summary>
        /// <param name="enchashPrice"></param>
        /// <returns></returns>
        public static decimal FastEnchashmentPoundage(decimal enchashPrice)
        {
            enchashPrice = enchashPrice * 0.0005m;
            //enchashPrice = (Math.Ceiling(enchashPrice * 100) / 100m) * CommonModel.EnchashmentMultiple;
            enchashPrice = Math.Round(Math.Round(enchashPrice, 2, MidpointRounding.AwayFromZero) * CommonModel.EnchashmentMultiple, 2, MidpointRounding.AwayFromZero);
            return enchashPrice < 0.01m ? 0.01m : enchashPrice;
        }

        /// <summary>
        /// 快速提现倍数
        /// </summary>
        private static int EnchashmentMultiple
        {
            get
            {
                object o = ConfigCenterWork.GetConfigValueByOperationType("currdateholiday");
                if (o != null)
                {
                    return Validates.GetInt(o);
                }
                return 1;
            }
        }


        #region 阿里安全防护

        /// <summary>
        /// 是否阿里防护白名单
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static bool AliPreventionWhite(string mobile)
        {
            ConfigCenterResponse centerResponse = ConfigCenterWork.GetCustomResponse("/existalisafe", string.Format("mobile={0}", mobile));
            return centerResponse.Code == 1;
        }

        /// <summary>
        /// 阿里验证码防护
        /// </summary>
        /// <param name="jsToken"></param>
        /// <param name="mobile"></param>
        /// <param name="type"></param>
        /// <param name="ip"></param>
        /// <param name="urlReffer"></param>
        /// <param name="agent"></param>
        /// <returns></returns>
        public static bool AliMessagePrevention(string jsToken, string mobile, string type, string ip, string urlReffer, string agent)
        {
            if (AliPreventionWhite(mobile))
            {
                return true;
            }
            int enabledAliPrevention = Validates.GetInt(ConfigCenterWork.GetConfigValueByOperationType(2) ?? 2);
            if (enabledAliPrevention == 0)
            {
                return true;
            }
            else if (string.IsNullOrEmpty(jsToken) && enabledAliPrevention == 2)
            {
                return false;
            }
            if (string.IsNullOrEmpty(jsToken))
            {
                return true;
            }

            MessagePreventionResponse messagePreventionResponse =
                Prevention.MessagePrevention(ip, mobile, 2, jsToken, urlReffer, agent)
                ?? new MessagePreventionResponse() { ErrorCode = 1, ErrorMsg = "阿里验证码安全防护返回null" };
            //NodeLog.NodeLogHandler.AddLog("tongdun", "ali", "短信验证码安全防护验证",
            //    string.Format("jsToken:{0}", jsToken), NodeLogType.info, new { type, mobile, data = messagePreventionResponse.Data });

            NodeLogHandler.AddLog("短信验证码安全防护验证", string.Format("jsToken:{0}", jsToken), NodeLogType.info,
                                          new { type, mobile, data = messagePreventionResponse.Data });
            if (messagePreventionResponse.ErrorCode != 0)
            {
                NodeLogHandler.AddLog("Prevention", "ali", "短信验证码安全防护失败",
                    string.Format("ErrorCode:{0},ErrorMsg:{1},jsToken:{2}",
                        messagePreventionResponse.ErrorCode, messagePreventionResponse.ErrorMsg, jsToken), NodeLogType.error,
                    new { type, mobile, data = messagePreventionResponse.Data });
            }
            else if (messagePreventionResponse.Data.FnalDecision == 1) //高风险
            {
                NodeLogHandler.AddLog("Prevention", "ali", "短信验证码安全防护拦截",
                    string.Format("jsToken:{0}", jsToken), NodeLogType.error, new { type, mobile, data = messagePreventionResponse.Data });
                return false;
            }
            else
            {
                NodeLogHandler.AddLog("Prevention", "ali", "短信验证码安全防护通过",
                     string.Format("jsToken:{0}", jsToken), NodeLogType.error, new { type, mobile, data = messagePreventionResponse.Data });
                return true;
            }

            return true;
        }

        /// <summary>
        /// 阿里注册安全防护
        /// </summary>
        /// <param name="jsToken"></param>
        /// <param name="mobile"></param>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool AliRegisterPrevention(string jsToken, string mobile, string ip)
        {
            if (AliPreventionWhite(mobile))
            {
                return true;
            }
            int enabledAliPrevention = Validates.GetInt(ConfigCenterWork.GetConfigValueByOperationType(2) ?? 2);
            if (enabledAliPrevention == 0)
            {
                return true;
            }
            else if (string.IsNullOrEmpty(jsToken) && enabledAliPrevention == 2)
            {
                return false;
            }
            if (string.IsNullOrEmpty(jsToken))
            {
                return true;
            }

            SpamRegisterPreventionResponse registerPreventionResponse =
                Prevention.SpamRegisterPrevention(mobile, RegisterIdentityType.PhoneNumber, ip, 2, jsToken)
                ?? new SpamRegisterPreventionResponse() { ErrorCode = 1, ErrorMsg = "阿里注册安全防护返回null" };
            //NodeLog.NodeLogQueueHandler.AddLog("阿里注册安全防护验证",
            //    string.Format("jsToken:{0}", jsToken), NodeLogType.info, new { mobile, data = registerPreventionResponse.Data });

            NodeLogHandler.AddLog("阿里注册安全防护验证", string.Format("jsToken:{0}", jsToken), NodeLogType.info,
                                          new { mobile, data = registerPreventionResponse.Data });

            if (registerPreventionResponse.ErrorCode != 0)
            {
                NodeLogHandler.AddLog("Prevention", "ali", "注册安全防护失败",
                    string.Format("ErrorCode:{0},ErrorMsg:{1},jsToken:{2}",
                        registerPreventionResponse.ErrorCode, registerPreventionResponse.ErrorMsg, jsToken), NodeLogType.info,
                    new { mobile, data = registerPreventionResponse.Data });
            }
            else if (registerPreventionResponse.Data.FnalDecision == 1) //高风险
            {
                NodeLogHandler.AddLog("Prevention", "ali", "注册安全防护拦截",
                    string.Format("jsToken:{0}", jsToken), NodeLogType.info, new { mobile, data = registerPreventionResponse.Data });
                return false;
            }
            else
            {
                NodeLogHandler.AddLog("Prevention", "ali", "注册安全防护通过",
                    string.Format("jsToken:{0}", jsToken), NodeLogType.info, new { mobile, data = registerPreventionResponse.Data });
                return true;
            }
            return true;
        }

        /// <summary>
        /// 阿里登录安全防护
        /// </summary>
        /// <param name="jsToken"></param>
        /// <param name="uName"></param>
        /// <param name="mobile"></param>
        /// <param name="ip"></param>
        /// <param name="accountExist"></param>
        /// <param name="passwordCorrect"></param>
        /// <param name="userStateGuid"></param>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public static bool AliLoginPrevention(string jsToken, string uName, string mobile, string ip, int accountExist, int passwordCorrect)
        {
            if (!string.IsNullOrEmpty(mobile) && AliPreventionWhite(mobile))
            {
                return true;
            }
            else if (Validates.IsMobile(uName) && AliPreventionWhite(uName))
            {
                return true;
            }
            int enabledAliPrevention = Validates.GetInt(ConfigCenterWork.GetConfigValueByOperationType(2) ?? 2);
            if (enabledAliPrevention == 0)
            {
                return true;
            }
            else if (string.IsNullOrEmpty(jsToken) && enabledAliPrevention == 2)
            {
                return false;
            }
            if (string.IsNullOrEmpty(jsToken))
            {
                return true;
            }

            string identity = string.IsNullOrEmpty(mobile) ? uName : mobile;
            RegisterIdentityType registerIdentityType = string.IsNullOrEmpty(mobile) ? RegisterIdentityType.UserId : RegisterIdentityType.PhoneNumber;
            if (registerIdentityType != RegisterIdentityType.PhoneNumber && Validates.IsMobile(identity))
            {
                registerIdentityType = RegisterIdentityType.PhoneNumber;
            }

            LoginPreventionResponse loginPreventionResponse = Prevention.LoginPrevention(identity, registerIdentityType, ip, 2, jsToken, accountExist, passwordCorrect)
                ?? new LoginPreventionResponse() { ErrorCode = 1, ErrorMsg = "阿里登录安全防护返回null" };

            NodeLogHandler.AddLog("阿里登录安全防护验证", string.Format("jsToken:{0}", jsToken), NodeLogType.info,
                                          new { uName, mobile, data = loginPreventionResponse.Data });
            if (loginPreventionResponse.ErrorCode != 0)
            {
                NodeLogHandler.AddLog("Prevention", "ali", "阿里登录安全防护失败",
                    string.Format("ErrorCode:{0},ErrorMsg:{1},jsToken:{2}", loginPreventionResponse.ErrorCode, loginPreventionResponse.ErrorMsg, jsToken),
                    NodeLogType.info, new { uName, mobile, data = loginPreventionResponse.Data });
            }
            else if (loginPreventionResponse.Data.FnalDecision == 1) //高风险
            {
                NodeLogHandler.AddLog("Prevention", "ali", "阿里登录安全防护拦截",
                    string.Format("jsToken:{0}", jsToken), NodeLogType.info, new { uName, mobile, data = loginPreventionResponse.Data });
                return false;
            }
            else
            {
                NodeLogHandler.AddLog("Prevention", "ali", "阿里登录安全防护通过",
                    string.Format("jsToken:{0}", jsToken), NodeLogType.info, new { uName, mobile, data = loginPreventionResponse.Data });
                return true;
            }
            return true;
        }

        #endregion
        /// <summary>
        /// 是否强制加密请求
        /// </summary>
        public static bool RequestCoerciveEncryption = ConfigurationManager.AppSettings["RequestCoerciveEncryption"] == "true";

        /// <summary>
        /// 微信公众号请求网址
        /// </summary>
        public static string WxRequestUrl
        {
            get
            {
                string url = ConfigurationManager.AppSettings["wxRequestUrl"] ?? "";
                return url;
            }
        }

        #region 活期产品配置信息

        /// <summary>
        /// 活期单日可提现最大金额
        /// </summary>
        public static int CurrentMaximumSellOutToOneDay
        {
            get
            {
                object o = ConfigCenterWork.GetConfigValueByOperationType(22);
                if (o != null)
                {
                    return Validates.GetInt(o);
                }
                return 0;
            }
        }

        /// <summary>
        /// 活期单个用户可持有最大金额
        /// </summary>
        public static int CurrentMaxHaveMoney
        {
            get
            {
                object o = ConfigCenterWork.GetConfigValueByOperationType(23);
                if (o != null)
                {
                    return Validates.GetInt(o);
                }
                return 0;
            }
        }

        /// <summary>
        /// 起投金额（最低购买金额及基数）
        /// </summary>
        public static int CurrentMinBuyMoney
        {
            get
            {
                object o = ConfigCenterWork.GetConfigValueByOperationType(24);
                if (o != null)
                {
                    return Validates.GetInt(o);
                }
                return 0;
            }
        }

        #endregion

    }

}